package com.practice.communication.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class ServerAsyncHandler implements Runnable {
	
	public CountDownLatch latch;
	public AsynchronousServerSocketChannel serverChannel;
	
	public ServerAsyncHandler(int port) {
		try {
			//创建服务端通道
			serverChannel = AsynchronousServerSocketChannel.open();
			
			//绑定端口
			serverChannel.bind(new InetSocketAddress(port));
			
			System.out.println("服务端已启动，端口号：" + port);
		} catch (IOException e) {
			
		} 
	}

	@Override
	public void run() {
		//CountDownLatch初始化
		//它的作用：在完成一组正在执行的操作之前，允许当前线程一直阻塞
		//此处，让线程在此阻塞，防止服务端完成后退出
		//也可以使用while(true)+sleep
		//生产环境就不需要担心这个问题，因为服务器是不会退出的
		latch  = new CountDownLatch(1);
		
		//用于接收客户端的连接
		serverChannel.accept(this, new ServerAcceptHandler());
		
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
